import { Component } from '@nestjs/common'
import * as request from 'request-promise'
import config from '../../config'

const settings = {
  assessToken: '',
  ticket: ''
}

@Component()
export class WechatService {
  constructor() { }

  // 用 code 获取网页授权token
  async getAccessTokenByCode(code: string): Promise<any> {
    const url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${config.wechat.appID}&secret=${config.wechat.appsecret}&code=${code}&grant_type=authorization_code`
    const userInfo = await request(url)
    return userInfo
  }

  async getAccessToken(): Promise<any> {
    const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.wechat.appID}&secret=${config.wechat.appsecret}`

    if (!settings.assessToken) {
      const tokenStr = await request(url)
      const tokenObj = JSON.parse(tokenStr)
      settings.assessToken = tokenObj.access_token
    }

    return Promise.resolve({ access_token: settings.assessToken })
  }

  async getJSAPITicket(accessToken: string): Promise<any> {
    const url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${accessToken}&type=jsapi`

    if (!settings.ticket) {
      const jsapiStr = await request(url)
      const jsapiObj = JSON.parse(jsapiStr)
      settings.ticket = jsapiObj.ticket
    }
    // console.log(jsapiObj)
    // return jsapiObj
    // const ticket = 'HoagFKDcsGMVCIY2vOjf9mIRvSTa_FOyfXtgaLkRBsC2rTpkPJNyfgjXQxUgQIlD_h_8mLTl-fIYxa9fj3oJHQ'
    return Promise.resolve({ ticket: settings.ticket })
  }

  async getJSAPITicketStraight() {
    const tokenObj = await this.getAccessToken()
    return await this.getJSAPITicket(tokenObj.access_token)
  }
}
